<?php
namespace frontend\models;

use Yii;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\behaviors\TimestampBehavior;
use yii\db\Exception;
date_default_timezone_set("PRC");

class PostsCollect extends ActiveRecord
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    const STATUS = 1;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%posts_collect}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return[
            [['id','posts_id','member_id','item_id','is_collect','is_like','status'], 'trim'],
            [['id','member_id'], 'required', 'message'=>'{attribute}不能为空'],
            [['is_collect','item_id'], 'required', 'message'=>'{attribute}不能为空','on'=>'create_project'],
            [['id','posts_id','member_id','item_id'], 'match', 'pattern' => '/^[1-9][0-9]*$/','message'=>'{attribute}值无效'],
        ];
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id'=>'收藏id',
            'posts_id'=>'帖子id',
            'member_id'=>'会员id',
            'item_id'=>'项目id',
            'is_collect'=>'是否收藏',
            'is_like'=>'是否点赞',
            'status'=>'状态值',
        ];
    }

    public function scenarios()
    {
        return [
            'default' => [
                'id',
                'posts_id',
                'member_id',
                'is_collect',
                'is_like',
                'status',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'create_posts' => [
                'posts_id',
                'member_id',
                'is_collect',
                'is_like',
                'status',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'create_project' => [
                'member_id',
                'item_id',
                'is_collect',
                'is_like',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'update_project' => [
                'member_id',
                'item_id',
                'is_collect',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'update' => [
                'id',
                'posts_id',
                'member_id',
                'item_id',
                'is_collect',
                'is_like',
                'status',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'like' => [

            ],
        ];
    }


    public static function like($data){
        $model = static::findOne(['posts_id' => $data['posts_id'],'member_id' => $data['member_id']]);
        //$res = $model->toArray();
        if(!empty($model)){
            $model->scenario = 'like';
            if($data['type'] == 'like'){
                if($data['is_click'] == 'yes'){
                    $model->is_like = 1;
                }else{
                    $model->is_like = 2;
                }
            }elseif ($data['type'] == 'collect'){
                if($data['is_click'] == 'yes'){
                    $model->is_collect = 1;
                }else{
                    $model->is_collect = 2;
                }
            }
            return $model->save();
        }else{
            $models = new static();
            $models->scenario = 'like';
            $models->posts_id = $data['posts_id'];
            $models->member_id = $data['member_id'];
            if($data['type'] == 'like'){
                if($data['is_click'] == 'yes'){
                    $models->is_like = 1;
                }else{
                    $models->is_like = 2;
                }
            }elseif ($data['type'] == 'collect'){
                if($data['is_click'] == 'yes'){
                    $models->is_collect = 1;
                }else{
                    $models->is_collect = 2;
                }
            }
            return $models->save();
        }
    }

    /**
     * @inheritdoc
     */
    public static function selectData($params,$field = '*')
    {
        $query = new \yii\db\Query();
        $query->select([$field])->from('posts_collect');
        $query->where(['deleted_at' => null]);
        $query->orderBy([
            'created_at' => SORT_DESC,
        ]);
        if(!empty($params['posts_id'])){
            $query->andWhere(['posts_id' => $params['posts_id']]);
        }
        if(!empty($params['is_collect'])){
            $query->andWhere(['is_collect' => $params['is_collect']]);
        }
        if(!empty($params['is_like'])){
            $query->andWhere(['is_like' => $params['is_like']]);
        }
        $command = $query->createCommand();
        $result = $command->queryAll();
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function findOneData($data,$field = '*')
    {
        $query = new \yii\db\Query();
        $query->select([$field])->from('posts_collect');
        $query->where(['deleted_at' => null]);
        if(!empty($data['id'])){
            $query->andWhere(['id' => $data['id']]);
        }
        if(!empty($data['posts_id'])){
            $query->andWhere(['posts_id' => $data['posts_id']]);
        }
        if(!empty($data['member_id'])){
            $query->andWhere(['member_id' => $data['member_id']]);
        }
        if(!empty($data['is_collect'])){
            $query->andWhere(['is_collect' => $data['is_collect']]);
        }
        if(!empty($data['is_like'])){
            $query->andWhere(['is_like' => $data['is_like']]);
        }

        $command = $query->createCommand();
        $result = $command->queryOne();
        if(!empty($result['created_at']))
            $result['created_at'] = date('Y-m-d',$result['created_at']);
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }



    /**
     * 收藏或取消收藏项目
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function projectCollect($params){
        if($params['is_collect'] == 2){ //取消收藏
            $model = static::findOne(['item_id' =>$params['item_id'],'member_id'=>$params['member_id']]);
            if(empty($model)) return array('error'=>'您暂未收藏该项目');
            $model->scenario = 'update_project';
        }elseif($params['is_collect'] == 1){
            $model = static::findOne(['item_id' =>$params['item_id'],'member_id'=>$params['member_id']]);
            if(empty($model)){
                $model = new self();
                $model->scenario = 'create_project';
            }else{
                $model->scenario = 'update_project';
            }
        }else{
            return array('error'=>'参数错误');
        }
        unset($params['id']);
        $t = static::getDb()->beginTransaction();
        try {
            $model->setAttributes($params, false);
            if (!$model->save()) {
                return array('error'=>'操作失败');
            }else{
                $model->refresh();
                $t->commit();
                return array('error'=>'');
            }
        }catch (Exception $e){
            $t->rollback();
            return array('error'=>'操作失败');
        }

    }




    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS]);
    }

    /**
     * @inheritdoc
     */
    public static function findDataByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}
